package org.benjamin.lending.service.impl;

import java.sql.Timestamp;

import javax.mail.internet.MimeMessage;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.entity.EmailLog;
import org.benjamin.lending.domain.entity.MemberInfo;
import org.benjamin.lending.domain.entity.Verify;
import org.benjamin.lending.domain.entity.VerifyType;
import org.benjamin.lending.repository.EmailLogRepository;
import org.benjamin.lending.repository.MemberInfoRepository;
import org.benjamin.lending.repository.VerifyRepository;
import org.benjamin.lending.service.EmailService;
import org.benjamin.lending.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

@Service("emailService")
public class EmailServiceImpl implements EmailService{
	
	private Logger logger = LogManager.getLogger();
	
	@Value("${mail.from}")
	private String mailFrom;

	@Autowired
	private MemberInfoRepository memberInfoRepository;

	@Autowired
	private VerifyRepository verifyRepository;

	@Autowired
	private EmailLogRepository emailLogRepository;

	@Autowired
	private SettingService settingService;
	
	@Autowired
	private SpringTemplateEngine templateEngine;
	
	@Autowired
	@Qualifier("mailSender")
	private JavaMailSender mailSender;
	
	@Autowired
	@Qualifier("mailMessage")
	private SimpleMailMessage simplateMailMessage;


	@Override
	public void getPassword(String email) throws Exception {
		MemberInfo memberInfo = this.memberInfoRepository.findByEmail(email);
		String domain = settingService.getSettingCodeAndKey("net","domain");
		if(StringUtils.isBlank(domain)){
			domain = "http://localhost:8080/lending-web";
		}
		String vcode = RandomStringUtils.random(32);
		vcode = DigestUtils.md5Hex(vcode);
		String link = "#DOMAIN#/commons/getPasswordVerify?vcode=#VCODE#";
		link = link.replace("#DOMAIN#", domain);
		link = link.replace("#VCODE#", vcode);
		logger.info("最终生成链接是：{}",link);
		Verify verify = new Verify();
		verify.setCode(vcode);
		verify.setUkey(memberInfo.getId());
		verify.setType(VerifyType.EMAILL);
		this.verifyRepository.save(verify);
		Context context = new Context();
		context.setVariable("UserName", memberInfo.getUsername());
		context.setVariable("LINKE", link);
		String template = this.templateEngine.process("getPasswordEmailTemplate.html", context);
		//String template = this.settingService.getSettingCodeAndKey("email","n");
		if(StringUtils.isBlank(template)){
			throw new IllegalArgumentException("系统出现问题：需要发送的模板不存在");
		}
		//String outTemplate = StringUtils.replaceEach(template, new String[]{"#UserName#", "#LINKE#"}, new String[]{memberInfo.getUsername(),link});
		this.sendEmail(memberInfo.getEmail(),"您刚刚在申请了密码找回",template,"html");
	}

	public void sendEmail(String address,String title,String message,String type) throws Exception {
		logger.info("短信发送内容：{}",message);
		if(this.sendEmailOperation(address,title,message,type)){
			EmailLog emailLog = new EmailLog();
			emailLog.setCreateTime(new Timestamp(System.currentTimeMillis()));
			emailLog.setContent(message);
			emailLog.setSender(address);
			emailLog.setTitle(title);
			this.emailLogRepository.save(emailLog);
		}
	}
	
	public boolean sendEmailOperation(String address,String title,String text,String type) throws Exception {
		if(type.equals("html")){
			MimeMessage message = this.mailSender.createMimeMessage();
			MimeMessageHelper messageHelper = new MimeMessageHelper(message);
			messageHelper.setFrom(this.mailFrom);
			messageHelper.setSubject(title);
			messageHelper.setText(text,true);
			messageHelper.setTo(address);
			this.mailSender.send(message);
		}else{
			this.simplateMailMessage.setSubject(title);
			this.simplateMailMessage.setText(text);
			this.simplateMailMessage.setTo(address);
			this.mailSender.send(simplateMailMessage);
		}
		return true;
	}

}
